/*******************************************************************************
 * Wait for required javascripts
 ******************************************************************************/
var showConsole = false;	// console window
var timer = setInterval('timeout()', 100);
var $j = null;	// for jQuery

function timeout(){
	if(GMLib && Prototype && jQuery){
		clearInterval(timer);
		if(showConsole) gmConsole.init();
		main();
	}
}


/*******************************************************************************
 * Write your code here
 ******************************************************************************/
function main(){

	$j = jQuery.noConflict();

	const SESSION_ID = THIS_URL_PARAMS.session;

	const ICON_REFRESH = 'data:image/gif;base64,'+
	'R0lGODlhDAAMALMAAP//AP/vAP+/AP+vAP+fAP+PAP9gYP8vAP8QEP8AAP///wAAAAAAAAAAAAAA'+
	'AAAAACH5BAUUAAoALAAAAAAMAAwAAAQ3UEmDUkJG6jqEKNdmHQEAEKFhjeWZUCtrEohg3vhp5zgd'+
	'J6QZJhZ0ZSrAFgoh6nxCGgXskpFEAAA7';

	var GALAXY_TD = null;
	const GALAXY_SCAN_RANGE=25;
	const RESOURCE = 3000;

	// ---------------------------------------------------------------------------


	function getRadioValue(rdo){
		for (i=0;i<rdo.length;i++) {
			if (rdo[i].checked) {
				return rdo[i].value;
			}
		}
		return "";
	}
	
	function markGalaxy(){
		var roles = ['inactive', 'vacation', 'noob'];
		$j.each(roles, function(i, role){
			var spans = $j("span."+role);
			$j.each(spans, function(i, span){
				var tr = span.parentNode.parentNode;
				if(tr.nodeName == 'TR'){
					$j(tr).addClass(role);
				}
			});			
		});		
	}

	function galaxy(){	

		markGalaxy();
		
		var system = parseInt($x0("//input[@name='system']").value);
		var b = $x0("//input[@type='submit']");

		b.parentNode.innerHTML += ' <input type="radio" name="rdo_range" value="beginend" CHECKED>'+
																'<input id="s_begin" type="text" size=3 value="'+(system-GALAXY_SCAN_RANGE)+'">~'+
																'<input id="s_end" type="text" size=3 value="'+(system+GALAXY_SCAN_RANGE)+'">'+
															' <input type="radio" name="rdo_range" value="plusminus" >'+
																'+/-<input id="s_plusminus" type="text" size=2 value="'+GALAXY_SCAN_RANGE+'">';

		var btn = _domCreateImgButton({
				img: ICON_REFRESH,
				hint: 'scan',
				events: [['click', scanGalaxy]]
		});
		$j(btn).insertAfter($j('#s_plusminus'));

		GALAXY_TD=_ce('div');
		GALAXY_TD.id = 'GALAXY_TD';
		GALAXY_TD.style.display = 'block';
		GALAXY_TD.innerHTML = 'Resources:';
		$j(GALAXY_TD).insertAfter($j('#galaxy_form'));
		/*
		var tr = $('fleetstatusrow');
		tr.parentNode.innerHTML += '<tr><td id="galaxy_td" colspan="8">Resource: </td></tr>';
		GALAXY_TD = $('galaxy_td');
		 */
	}

	function scanGalaxy(){
		GALAXY_TD.innerHTML = 'Resources:';
		//_log('scanGalaxy()');
		var url = 'http://'+document.location.host+'/game/galaxy.php?session='+SESSION_ID+'&galaxyLeft=dr&system=';

		// check selected option
		var rdo = $x("//input[@name='rdo_range']");
		//_log(getRadioValue(rdo));
		if(getRadioValue(rdo)=='plusminus'){
			var system = parseInt($x0("//input[@name='system']").value);
			var newScanRange = parseInt($('s_plusminus').value);
			$('s_begin').value = system-newScanRange;
			$('s_end').value = system+newScanRange;
		}

		var s1 = parseInt($('s_begin').value);
		var s2 = parseInt($('s_end').value);
		_log(s1 + '~' + s2);

		for(var i=s1; i<=s2; i++){
			if(i<0) continue;
			_ajax(
				url+i,
				function(r, userData) {
					scanGalaxyOk(_getAjaxHtmlBody(r), userData.system, userData.url);
				},
				{
					system: i,
					url: url+i
				}
			);
		}
	}

	function scanGalaxyOk(html, system, url){
		//_log('scanGalaxyOk(): '+system);
		var galaxy = $x0("//input[@name='galaxy']").value;

		var div = _domInsertHddenHtml(html);
		try{
			var ths = $x("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//tr/th[5]");
			// _log(ths.length);

			var res = [];
			ths.each(function(th,i){
				if(th.innerHTML.search('<img')<=0) return;	// ignore no-resource

				// check how much resource here
				var a = th.childNodes[1];
				//_log(a.innerHTML);
				var s = a.getAttribute('onmouseover').match(/<table>.*<\/table>/gi);
				//_log(s);

				// parse html
				var d = _ce('div');
				d.id = 'resource_div';
				d.innerHTML = s;
				document.body.appendChild(d);
				d.style.display = 'none';
				try{
					var rths = $x("//div[@id='resource_div']//th[2]");
					//_log('rths: '+rths.length);
					var metal = parseInt(rths[0].innerHTML.replace('.', ''));
					var crystal = parseInt(rths[1].innerHTML.replace('.', ''));
					_log('['+galaxy + ':'+ system + ':' + (i+1) +'] = (' + metal + ',' + crystal + ')');
					var r = metal+crystal;
					if(r>=RESOURCE){
						res.push({
							planet: i+1,
							resource: r
						})
					}
				}finally{
					_del(d);
				}

			});

			// havest the resource: doit(8, galaxy, system, plant, 2, hval);
			// where hval is number of ships, every ship can carry 20,000 resource units
			res.each(function(r){
				var recyclers = Math.ceil(r.resource/20000);
				var color='#0f0';	// green
				var size = 11;
				if(recyclers>5){
					color = '#f00';	// red
					size = 19;
				}else if(recyclers>1){
					color = '#ff0';	// yellow
					size = 15;
				}

				GALAXY_TD.innerHTML += '<span style="font-size:'+size+'px;"><a target="_blank" href="'+url+'">'+
						system+ ':' + r.planet +
					'</a>'+
					'(<a href="#" style="color:'+color+' !important;" onclick="'+
							'doit(8,'+galaxy+','+system+','+r.planet+',2,'+recyclers+');'+
							'this.style.display=\'none\';">'+
							recyclers + ':' + r.resource + '</a>)</span>, ';
			});

		}finally{ div.innerHTML = '';	}
	}

	function leftmenu(){
		// open overview link
		var a = $j("a[href*='page=overview']")[0];
		if(a){			
			var b = a.cloneNode(true);
			b.innerHTML = ' (All)';
			b.href = '#';
			b.addEventListener('click', overview_all, true);
			$j(b).insertAfter(a);
			
			// set a.target
			a.target = '_blank';
		}

		a = $j("a[href*='page=flotten1']")[0];
		if(a){
			var b = a.cloneNode(true);
			b.innerHTML = ' (All)';
			b.href += '&all=yes';
			$j(b).insertAfter(a);
		}		
	}
	
	function overview(){		
		// replace image with planet name
		var resources = $j("//font[contains(@color,'#')]/ancestor::table[contains(@width,'100%')]/tbody/tr[3]/td[position()<5 and position()>1]");
		var values = [];
		//resources.each(function(r,i){
		$j.each(resources, function(i, r){
			if(i<=2)
				values.push(r.textContent);
		});
		var txt = _ce('b');
		var sel = $j("select")[0];		
		var url = 'http://' + document.location.host + sel.options[sel.selectedIndex].value;		
		txt.innerHTML = sel.options[sel.selectedIndex].textContent.replace('[','<br>[') +
			'<br><a href="'+url+'">' + values.toString().replace(/\,/g, '<br>') + '</a>';
		_replace(txt, $x0("//th[@colspan='2']/img"));

		// update rename planet link
 		var a = $x("//a[contains(@href,'page=renameplanet')]");	 // fail to use $j()
 		_log('a.length='+a.length);
		var planetA = (a.length==2? a[1]: a[0]);
		if(a.length==2){
			a[1].href = a[0].href;
		}
	
 		var note = _ce('span');
		note.innerHTML = ' <font color="#ffff00">Note: Disable Javascript Before you click it!</font>';
		$j(note).insertAfter(planetA.nextSibling);
 
		// add form to delete/rename planet
		var form = _ce('form');
		form.setAttribute('method', 'post');
		form.setAttribute('action', planetA.href);
		form.innerHTML = '<input type="text" name="newname" size="25" maxlength="20">' +
			'<input type="submit" name="aktion" value="rename">' +
			'<input type="submit" name="aktion" value="abandon colony" alt="abandon the colony">';
		$j(form).insertAfter(planetA.nextSibling);

		// mark return flight message
/* 		var trs = $j("tr.flight");
		_log('trs.length='+trs.length);
		$j.each(trs, function(i, tr){
			var tr_id = 'tr_flight'+i;
			$j(tr).attr('id', tr_id);
			if($j("//tr[@id='"+tr_id+"']//a[@class='owndeploy']").length < 2){
				$j(tr).addClass('return');
			}
		});
 */
		// mark busy planet
		var centers = $j("br + center");
		_log('centers.length='+centers.length);
		$j.each(centers, function(i, c){
			var s = c.textContent.trim();
			_log(s + '-' + s.length);
			if(s.length!=2 && s.indexOf('free')<0){
				$j(c.parentNode).addClass('busy');
			}
		});
		
		// get all planets' resources
		overview_all();
		
	}

	
	function overview_all(){
		
		if(/page\=overview/.test(THIS_URL) == false){
			return;
		}		
		
		// get glaxy resources using ajax
		var as = $x("//a[contains(@href,'page=overview')]");
		as.each(function(a){
			_addClass(a.parentNode, 'ogame_glaxy_info');
			var url = a.href;
			var i=url.indexOf('cp=');
			var cp = url.substring(i+3, url.length);
			_log(cp);
			_log(url);
			_ajax(url,
						function(r, userData){
							processGlaxyInfo(_getAjaxHtmlBody(r), userData.cp);
						},
						{
							cp: cp
						}
			);
		});

		// after that, query current glaxy
		var sel = $j("select")[0];	
		var url = 'http://' + document.location.host + sel.options[sel.selectedIndex].value;
		_log(url);
		_ajax(
			url,
			function(r){
				// do nothing
			}
		);

	}

	function processGlaxyInfo(html, cp){
		var div = _domInsertHddenHtml(html);
		try{
			//var resources = $x("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//font[contains(@color,'#')]/ancestor::table[contains(@width,'100%')]/tbody/tr[3]/td[position()<5 and position()>1]");
			var resources = $x("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//font/ancestor::table[@class='header']/tbody/tr[3]/td[position()<4]");
			_log('resources.length='+resources.length);
			var values = [];
			resources.each(function(r,i){
				//if(i<=2)
					values.push(r.textContent);
			});
			_log('values='+values);
			var resValue = values.toString().replace(/\,/g, '<br>');

			var a_glaxy = $x0("//a[contains(@href, 'cp="+cp+"')]");
			if(a_glaxy){
				var th = a_glaxy.parentNode;

				var i = th.innerHTML.indexOf('</a>');
				var txt = th.innerHTML.substring(i+4, th.innerHTML.length);

				var sel = $x0("//div[@id='"+OBJ_ID_HIDDEN_DIV+"']//select");
				th.innerHTML = sel.options[sel.selectedIndex].textContent.replace('[','<br>[') +
					'<br><a href="'+ a_glaxy.href +'">' + resValue + '</a>' + txt;

			}
		}finally{ div.innerHTML = '';	}
	}

	function messages(){
		// set list menu
		$x("//select[contains(@name, 'deletemessages')]").each(function(s){
			s.options[1].selected = 'true'; // unmarked messages
			_log(s.value);
		});

		// mark combat reports
		var rptSpans = $x("//span[@class='combatreport']");
		rptSpans.each(function(s){
			var tr = s.parentNode.parentNode.parentNode;
			var input = _t(tr, 'input')[0];
			input.checked = true;
		});
	}

	function fleet1(){
		// set to max fleet
		$x("//input").each(function(i){
			if(i.value==0){
				_log(i.name);
				try{
					i.value = $x0("//input[@name='max"+i.name+"']").value;
				}catch(e){ _log(e); }
			}
		});

		if(THIS_URL_PARAMS.all==='yes')
			_submitForm($x0("//form[contains(@action, 'page=flotten2')]"));
	}

	function fleet3(){
		$j("input[id='inpuT_0']")[0].checked = true;
		maxResources();

		function noResource(){
			$j("input[name='resource1']").value=0;
			$j("input[name='resource2']").value=0;
			$j("input[name='resource3']").value=0;
		}
		var js = noResource.toString();
		_insertJS(js);

		var a = $x0("//th[@colspan=3]/a");
		var b = a.cloneNode(true);
		b.href = 'javascript: noResource()';
		b.innerHTML = ' (no resource)';
		$j(b).insertAfter(a);
	}


	function b_building(){
		hide_building_images();
	}
	function buildings(){
		hide_building_images();
	}
	function hide_building_images(){
		var imgs = $x("//a[contains(@href,'page=infos')]/img");
		imgs.each(function(img){
			img.style.display = 'none';
		});
	}

	function resources(){
		var inputCalc = $x0("//input[@name='action']");
		if(inputCalc){
			// 100%
			var buttonAll = _ce('button');
			buttonAll.innerHTML = '100%';
			$j(buttonAll).insertAfter(inputCalc);
			buttonAll.addEventListener('click', function(e){
				// set buttonAll select items to 100%
				var sels = $x("//select[contains(@name, 'last')]");
				sels.each(function(s){
					s.selectedIndex = 0;
				});
				// submit the form
				_submitForm($x0("//form[@id='ressourcen']"));
			}, true);

			// 0%
			var buttonAll0 = _ce('button');
			buttonAll0.innerHTML = '0%';
			$j(buttonAll0).insertAfter(inputCalc);
			buttonAll0.addEventListener('click', function(e){
				// set buttonAll0 select items to 100%
				var sels = $x("//select[contains(@name, 'last')]");
				sels.each(function(s){
					s.selectedIndex = 10;
				});
				// submit the form
				_submitForm($x0("//form[@id='ressourcen']"));
			}, true);

			// <br>
			$j(inputCalc).after('<br>');
		}
	}

	// ---------------------------------------------------------------------------

	// check url to decide which function to execute
	//if(/page\=leftmenu\.php/.test(THIS_URL)){
	//	_log('leftmenu');
		leftmenu();
	//}

	if(/page\=galaxy/.test(THIS_URL)){
		_log('galaxy');
		galaxy();
	}

	if(/page\=overview/.test(THIS_URL)){
		_log('overview');
		overview();
	}

	if(/page\=messages/.test(THIS_URL)){
		_log('messages');
		messages();
	}

	if(/page\=flotten1/.test(THIS_URL)){
		_log('fleet1');
		fleet1();
	}

	if(/page\=flotten3/.test(THIS_URL)){
		_log('fleet3');
		fleet3();
	}
	if(/page\=buildings/.test(THIS_URL)){
		_log('buildings');
		buildings();
	}
	if(/page\=b_building/.test(THIS_URL)){
		_log('b_building');
		b_building();
	}

	if(/page\=resources/.test(THIS_URL)){
		_log('resources');
		resources();
	}

}

